from __future__ import annotations
from typing import Optional
from sqlalchemy.orm import Mapped, mapped_column, relationship
from extensions import db
from datetime import datetime
from sqlalchemy import func

class CardPackage(db.Model):
    """卡包模型"""
    __tablename__ = 'card_packages'

    # 自增主键ID，系统内部使用的唯一标识
    id: Mapped[int] = mapped_column(db.Integer, primary_key=True)
    # 卡包唯一标识符，使用UUID格式作为唯一标识
    package_id: Mapped[Optional[str]] = mapped_column(db.String(36), unique=True, index=True, nullable=True)
    # 卡包名称
    name: Mapped[Optional[str]] = mapped_column(db.String(100), nullable=True)
    # 计费类型（默认卡：default, 综合卡：comprehensive，按次计费卡：per_use）
    card_type: Mapped[Optional[str]] = mapped_column(db.String(20), nullable=True)
    # 总数量（综合卡时为总金额，按次计费卡时为总次数）
    total_amount: Mapped[Optional[float]] = mapped_column(db.Float, nullable=True)
    # 剩余数量（综合卡时为剩余金额，按次计费卡时为剩余次数）
    remaining_amount: Mapped[Optional[float]] = mapped_column(db.Float, nullable=True)
    # 销售提成金额
    commission_amount: Mapped[Optional[float]] = mapped_column(db.Float, nullable=True, default=0.0)
    # 销售提成比例（百分比）
    commission_rate: Mapped[Optional[float]] = mapped_column(db.Float, nullable=True, default=0.0)
    
    # 客户打折
    discount_rate: Mapped[Optional[float]] = mapped_column(db.Float, nullable=True, default=1.0)
    
    # 充值金额
    recharge_amount: Mapped[Optional[float]] = mapped_column(db.Float, nullable=True, default=0.0)
    # 赠送金额
    gift_amount: Mapped[Optional[float]] = mapped_column(db.Float, nullable=True, default=0.0)
    # 购买截止时间
    expiry_date: Mapped[Optional[datetime]] = mapped_column(db.DateTime, nullable=True)
    # 所属客户ID
    user_id: Mapped[Optional[str]] = mapped_column(db.String(36), nullable=True)
    # 所属店铺ID
    store_id: Mapped[Optional[str]] = mapped_column(db.String(36), nullable=True)
    # 父卡包ID（用于标识卡包来源）
    parent_card_package_id: Mapped[Optional[str]] = mapped_column(db.String(36), nullable=True)
    is_deleted: Mapped[Optional[bool]] = mapped_column(db.Boolean, default=False, nullable=True)

    def __init__(self, package_id: str, name: str, card_type: str, total_amount: float,
                 store_id: str, user_id: Optional[str] = None, expiry_date: Optional[datetime] = None, 
                 commission_amount: Optional[float] = None,
                 remaining_amount: Optional[float] = None,
                 recharge_amount: Optional[float] = None, 
                 gift_amount: Optional[float] = None,
                 commission_rate: Optional[float] = None, 
                 discount_rate: Optional[float] = None,
                 parent_card_package_id: Optional[str] = None,
                  is_deleted: Optional[bool] = None):  # 新增参数
        self.package_id = package_id
        self.name = name
        self.card_type = card_type
        self.total_amount = total_amount
        self.remaining_amount = remaining_amount if remaining_amount is not None else total_amount
        self.commission_amount = commission_amount
        self.recharge_amount = recharge_amount
        self.gift_amount = gift_amount
        self.expiry_date = expiry_date
        self.store_id = store_id
        self.user_id = user_id  # 新增用户ID参数
        self.commission_rate = commission_rate
        self.discount_rate = discount_rate
        self.parent_card_package_id = parent_card_package_id  # 新增初始化
        self.is_deleted = is_deleted if is_deleted is not None else False  # 新增初始化

    # 记录创建时间
    created_at: Mapped[Optional[datetime]] = mapped_column(
   db.DateTime, 
        server_default=func.now(),  # 使用数据库当前时间
        default=datetime.now,       # 使用Python系统时间作为后备
        onupdate=datetime.now,       # 更新时使用Python系统时间
        nullable=True
    )
    # 记录更新时间
    updated_at: Mapped[Optional[datetime]] = mapped_column(
  db.DateTime, 
        server_default=func.now(),  # 使用数据库当前时间
        default=datetime.now,       # 使用Python系统时间作为后备
        onupdate=datetime.now,       # 更新时使用Python系统时间
        nullable=True
    )

    def to_dict(self) -> dict:
        """将模型转换为字典"""
        return {
            'id': self.id,
            'package_id': self.package_id,
            'name': self.name,
            'card_type': self.card_type,
            'total_amount': self.total_amount,
            'remaining_amount': self.remaining_amount,
            'commission_amount': self.commission_amount,
            'commission_rate': self.commission_rate,
            'discount_rate': self.discount_rate,
            'recharge_amount': self.recharge_amount,
            'gift_amount': self.gift_amount,
            'expiry_date': self.expiry_date.isoformat() if self.expiry_date else None,
            'store_id': self.store_id,
            'parent_card_package_id': self.parent_card_package_id,  # 新增字段
            'created_at': self.created_at.isoformat() if self.created_at else None,
            'updated_at': self.updated_at.isoformat() if self.updated_at else None,
             'is_deleted': self.is_deleted 
        }
    # 关联关系（不使用外键约束）
    customer = relationship(
        'User',
        primaryjoin='CardPackage.user_id == User.id',
        backref='card_packages',
        foreign_keys=[user_id]
    )
    store = relationship(
        'Store',
        primaryjoin='CardPackage.store_id == Store.id',
        backref='card_packages',
        foreign_keys=[store_id]
    )